import { Module } from 'vuex'
import router from '@/router'

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login'
import localCache from '@/utils/cache'

import { ILoginState } from './types'
import { IRootState } from '../types'
import { IAccount } from '@/service/login/type'
import { mapMenusToRoutes, mapMenusToPermission } from '@/utils/map-menus'
import { ElMessage } from 'element-plus'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      menusPermission: []
    }
  },
  mutations: {
    saveToken(state, token: string) {
      state.token = token
    },
    saveUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    saveUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      // 1.注册动态路由
      // 将userMenus里的url映射到routes里
      const routes = mapMenusToRoutes(userMenus)
      // 将routes添加到router.main.children里
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 2.获取type=3的菜单权限
      const permission = mapMenusToPermission(userMenus)
      state.menusPermission = permission
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      // 1.实现登录逻辑
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('saveToken', token)
      localCache.setCache('token', token)

      // 存储token后进行完整的请求role和department数据
      dispatch('getInitialDataAction', null, { root: true })

      // 2.请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('saveUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('saveUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)

      // 4.登录成功的弹窗提示
      ElMessage({
        message: '登录成功',
        type: 'success'
      })

      // 5.跳转到首页
      router.push('/main')
    },
    // 刷新时重新将数据从localstorage里赋值给vuex
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('saveToken', token)
        // 刷新时,存储token后进行完整的请求role和department数据
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('saveUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('saveUserMenus', userMenus)
      }
    }
  }
}

export default loginModule
